# from info.modules.index import index_blue
from . import index_blue
from flask import render_template,current_app,session,make_response,g
from info.models import User,News,Category
from flask_wtf.csrf import generate_csrf
from info.utils.commons import user_login_data

# 功能:404页面响应
@index_blue.route('/404')
@user_login_data
def page_not_found():
    return render_template("news/404.html",data={ "user_info":g.user.to_dict() if g.user else g.user})

@index_blue.route('/')
@user_login_data
def index():
    # 查询新闻数据
    news = News.query.order_by(News.clicks.desc()).limit(10).all()

    # 查询分类信息,复习: 只要一个类继承自db.Model后,那么该模型类身上就会继承query属性; 作用: 获取查该模型类对应的查询结果集(sql语句)
    categories = Category.query.all()

    # 构建响应数据
    data = {
        "user_info":g.user.to_dict() if g.user else g.user,
        "news":news,
        "categories":categories
    }

    # 根据模板创建响应体对象
    response = make_response(render_template('news/index.html', data=data))

    # 在cookie中设置csrf_token
    response.set_cookie("csrf_token",generate_csrf())

    # 返回响应
    return response

# 功能: 展示网站logo
@index_blue.route('/favicon.ico')
def web_logo():
    return current_app.send_static_file("news/favicon.ico")